
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import java.util.Arrays;
import java.util.Random;

@SuppressWarnings("serial")
public class Launcher extends JFrame{

	public static void main(String[] args){
		Launcher myLauncher = new Launcher();
		myLauncher.setVisible(true);
	}
	
	static boolean[] completionArray;
	
	public Launcher() {
		this.setTitle("Ludos");
		this.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
		//this.setExtendedState(this.getExtendedState() | JFrame.MAXIMIZED_BOTH); 
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				saveCompletion();
				System.exit(0);
			}
		});
		initializeCompletionArray();
		this.add(new LauncherJPanel());
	}

	//Static functions for saving

	public static void saveCompletion() {
		try{
			// Create file 
			BufferedWriter out = new BufferedWriter(new FileWriter(System.getProperty("user.dir") + "\\resources\\save"));
			for (int i = 0; i < completionArray.length; i++) {
				out.write(completionArray[i] ? "1":"0");
				if (i + 1 < completionArray.length)
					out.write(",");
			}
			out.close();
		}catch (Exception e){//Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
	}


	private void initializeCompletionArray() {
		String sForArray = null;
		try {
			BufferedReader in = new BufferedReader(new FileReader(System.getProperty("user.dir") + "\\resources\\save"));
			sForArray = in.readLine();
			in.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (sForArray != null && sForArray.length() > 0){
			String[] parsed = sForArray.split(",");
			completionArray = new boolean[parsed.length];
			for (int i = 0; i < parsed.length; i++) {
				completionArray[i] = parsed[i].equals("1") ? true : false;
			}
		} else {
			completionArray = new boolean[5];
			Arrays.fill(completionArray, false);
		}
	}



	
	/*Function Used for Initialization*/
	
	
	//JFrame Inner class

	class LauncherJPanel extends JPanel implements MouseMotionListener{
		
		RotSquare leftRotSquare;
		RotSquare rightRotSquare;

		LauncherJPanel() {
			initRotSquares();
			addButtons();
			addMouseMotionListener(this);
		}
		//Initializes the splitting rhombi
		private void initRotSquares(){
			BufferedImage image;
			int numberOfCompleted = 1;
			for(int i = 0; i < completionArray.length; i++)
				if (completionArray[i])
					numberOfCompleted++;
			try {      
				Random rand = new Random();
				image = ImageIO.read(new File(System.getProperty("user.dir") + "\\resources\\images\\launcherTop" 
						+ rand.nextInt(numberOfCompleted >= 5 ? 5 : numberOfCompleted) + ".jpg"));
				int[][] rgbSubArrayL = new int[ROTSQUARE_WIDTH / 2][ROTSQUARE_HEIGHT];
				for (int i = 0; i < ROTSQUARE_WIDTH / 2; i++)
					for (int j = 0; j < ROTSQUARE_HEIGHT; j++) 
						rgbSubArrayL[i][j] = image.getRGB(i, j);
				leftRotSquare = new RotSquare(new Point(ROTSQUARE_X_OFFSET, ROTSQUARE_Y_OFFSET),
						new Point(ROTSQUARE_X_OFFSET + ROTSQUARE_WIDTH / 2, ROTSQUARE_Y_OFFSET + ROTSQUARE_HEIGHT),
						rgbSubArrayL, this);
				int[][] rgbSubArrayR = new int[ROTSQUARE_WIDTH / 2][ROTSQUARE_HEIGHT];
				for (int i = ROTSQUARE_WIDTH / 2; i < ROTSQUARE_WIDTH; i++)
					for (int j = 0; j < ROTSQUARE_HEIGHT; j++)
						rgbSubArrayR[i - ROTSQUARE_WIDTH / 2][j] = image.getRGB(i, j);
				rightRotSquare = new RotSquare(new Point(ROTSQUARE_X_OFFSET + ROTSQUARE_WIDTH / 2, ROTSQUARE_Y_OFFSET),
						new Point(ROTSQUARE_X_OFFSET + ROTSQUARE_WIDTH, ROTSQUARE_Y_OFFSET + ROTSQUARE_HEIGHT),
						rgbSubArrayR, this);
			} catch (IOException ex) {
				// handle exception...
				System.out.println("Unable to read file: " + System.getProperty("user.dir") + "\\resources\\images\\launcherTop.jpg");
			}
		}
		//Adds the button to the display to launch the games
		private void addButtons() {
			this.setBorder(BorderFactory.createEmptyBorder(ROTSQUARE_Y_OFFSET + ROTSQUARE_HEIGHT + BUTTON_SPACING,
					ROTSQUARE_X_OFFSET + 100, BUTTON_SPACING, ROTSQUARE_X_OFFSET + 110));
	        this.setLayout(new GridLayout(2, 3, BUTTON_SPACING * 2, BUTTON_SPACING));
	        
	        JButton towerDefenseB = new JButton("Tower Defense");
	        JButton miniGamesB = new JButton("The Mini Challenge");
	        JButton breakoutB = new JButton("Breakout");
	        JButton snakeB = new JButton("Snake");
	        JButton duckHuntB = new JButton("Shoot the Popups");
	        JButton unlockB = new JButton("Unlocked Features");
	        
	        breakoutB.addActionListener(new ActionListener() {
	        	 
	            public void actionPerformed(ActionEvent e)
	            {
	                //Execute when button is pressed
	            	
	            }
	        });
	        
	        snakeB.addActionListener(new ActionListener() {
	        	 
	            public void actionPerformed(ActionEvent e)
	            {
	                //Execute when button is pressed
	                new Snake();
	            }
	        });
	        
	        unlockB.addActionListener(new ActionListener() {
	        	 
	            public void actionPerformed(ActionEvent e)
	            {
	                //Execute when button is pressed
	                new UnlockFeatures();
	            }
	        });
			
			this.add(towerDefenseB);
			this.add(miniGamesB);
			this.add(breakoutB);
			this.add(snakeB);
			this.add(duckHuntB);
			this.add(unlockB);
		}

		public void paintComponent(Graphics g) {
			super.paintComponent(g);
			
			/*BufferedImage image;
			try {                
				image = ImageIO.read(new File(System.getProperty("user.dir") + "\\resources\\images\\launcherTop.jpg"));
				g.drawImage(image, ROTSQUARE_X_OFFSET, ROTSQUARE_Y_OFFSET, null);
			} catch (IOException ex) {
				System.out.println("Unable to read file: " + System.getProperty("user.dir") + "\\resources\\images\\launcherTop.jpg");
				// handle exception...
			}*/ //Remove this block ~!~
			
			
			leftRotSquare.drawRotSquare(g);
			rightRotSquare.drawRotSquare(g);
		}
		@Override
		public void mouseDragged(MouseEvent e) {
			// TODO Auto-generated method stub
			
		}
		@Override
		public void mouseMoved(MouseEvent e) {
			// TODO Auto-generated method stub
			
			//if (leftRotSquare.hasMousePointer(e))
			//	leftRotSquare.splitRotSquare(e);
			//else if (rightRotSquare.hasMousePointer(e))
			//	rightRotSquare.splitRotSquare(e);
			
			//change to use has mouse pointer
			if (e.getX() >= ROTSQUARE_X_OFFSET && e.getX() <= ROTSQUARE_X_OFFSET + ROTSQUARE_WIDTH / 2
				&& e.getY() >= ROTSQUARE_Y_OFFSET && e.getY() <= ROTSQUARE_Y_OFFSET + ROTSQUARE_HEIGHT){
				leftRotSquare.splitRotSquare(e);
			}
			else if (e.getX() <= ROTSQUARE_X_OFFSET + ROTSQUARE_WIDTH && e.getX() >= ROTSQUARE_X_OFFSET + ROTSQUARE_WIDTH / 2
					&& e.getY() >= ROTSQUARE_Y_OFFSET && e.getY() <= ROTSQUARE_Y_OFFSET + ROTSQUARE_HEIGHT){
				rightRotSquare.splitRotSquare(e);
			}
				
		}

	}

	//Constants
	public static final int WINDOW_WIDTH = 1300;
	public static final int WINDOW_HEIGHT = 700;
	
	private static final int ROTSQUARE_X_OFFSET = 125;
	private static final int ROTSQUARE_Y_OFFSET = 15;
	private static final int ROTSQUARE_WIDTH =  1024; //Ideally the width should be twice the height
	private static final int ROTSQUARE_HEIGHT = 512; //Ideally should be some power of 2
	
	private static final int BUTTON_SPACING = 20;
}
